package com.danci.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danci.common.Result;
import com.danci.dto.UserRequest;
import com.danci.entity.Sign;
import com.danci.entity.Userinfo;
import com.danci.mapper.LexiconMapper;
import com.danci.mapper.SignMapper;
import com.danci.mapper.UserinfoMapper;
import com.danci.service.ISignService;
import lombok.AllArgsConstructor;
import org.ehcache.impl.config.persistence.UserManagedPersistenceContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 签到表 服务实现类
 * </p>
 *
 * @author xxx
 * @since 2024-05-13
 */
@Service
@AllArgsConstructor
public class SignServiceImpl extends ServiceImpl<SignMapper, Sign> implements ISignService {

    private final SignMapper signMapper;
    private final LexiconMapper lexiconMapper;
    private final UserinfoMapper userinfoMapper;
    private final StringRedisTemplate redisTemplate;


    private static final String SIGN_KEY_PREFIX = "user:sign:";

    @Override
    public Result sign(UserRequest userRequest) {
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = SIGN_KEY_PREFIX + userRequest.getUserId() + keySuffix;
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        Boolean result = redisTemplate.opsForValue().getBit(key, now.getDayOfMonth()- 1);
        if (Boolean.TRUE.equals(result)){
            return Result.success("今天已经签到过了");
        }else {
            redisTemplate.opsForValue().setBit(key, dayOfMonth -1, true);
            return Result.success("签到成功");
        }
        //5. 写入redis setbit key offset 1

    }

    @Override
    public Result getSignStatus(UserRequest userRequest) {
        Map<String,Object> result = new HashMap<>();
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = SIGN_KEY_PREFIX + userRequest.getUserId() + keySuffix;
        Boolean ok = redisTemplate.opsForValue().getBit(key, now.getDayOfMonth()- 1);
        result.put("signStatus",ok);
        Userinfo userinfo = userinfoMapper.selectById(userRequest.getUserId());
        String lid = userinfo.getLid();
        if (lid == null){
            result.put("toLearn",0);
            result.put("toReview",0);
        }else {
            // 待学习 待复习的单词数量
            Map<String, Object> indexData = lexiconMapper.getIndexData(lid, userRequest.getUserId());
            result.put("toLearn",indexData.get("count"));
            result.put("toReview",indexData.get("learn_count1"));
        }

        return Result.success(result);
    }
}
